const userDao = require('../dao/userDao')
const encryption = require('../lib/encryption')
const passport = require('../middleware/passport')
const indexService = require('../service/indexService')
module.exports = {
    index:async(ctx,next)=>{
        await ctx.render('index', {
            title: 'Hello Koa MVC!'
        })
    },
    login:async(ctx,next)=>{
        await ctx.render('login', {})
    },
    error:async(ctx,next)=>{ //错误处理路由的对应controller
        await ctx.render('error', {
            message:ctx.session.errorMsg
        })
    },
    checkLogin:async(ctx,next)=>{
        // // console.log("1111");
        // // const {username,password} = ctx.request.body;//把login.html中提交的用户名和密码赋值给request.body
        // const {phone,password} = ctx.request.body;
        // // console.log(phone);
        // // console.log(username);
        // // console.log(password);
        // let user = await indexService.checkLogin(phone,password)
        // // console.log(checkValue);
        // if(user){
        //     ctx.session.username = user.username;
        //     ctx.response.redirect('/home')
        // }else{
        //     await ctx.render('login',{
        //         info:'账号或密码错误'
        //     });
        // }
        return passport.authenticate('local',async(err,user,info)=>{
            if(err){
                ctx.session.errorMsg = "passport 本地验证策略错误";
                ctx.response.redirect('/error');
            }
            if(!user){
                ctx.session.logInfo = "账号密码错误";
                ctx.response.redirect('/login');
            }else{
                ctx.login(user)
                ctx.response.redirect('/home');
            }
        })(ctx)
    },
    logout:async(ctx,next)=>{
        ctx.logout();
        ctx.response.redirect('/');
    },
    home:async(ctx,next)=>{
        await ctx.render('homeIndex',{
            // user:ctx.session.username,
            user:ctx.state.user,
        });
    },

    userManage:async(ctx,next)=>{
        let roles = await userDao.getAllRoles();
        console.log(roles)
        await ctx.render('userManage', {
            seachUserData:{
                roles:roles,
                opUserInfo:ctx.session.opUserInfo
            }
        })
    },
    searchUser:async(ctx,next)=>{
        console.log("111111");
        let searchusers = await indexService.seachUserByInfo(ctx.request.body);
        let roles = await userDao.getAllRoles();
        await ctx.render('userManage',{
            seachUserData:{
                roles:roles,
                users:searchusers,
                opUserInfo:''
            }
        })
    },
    addUser:async(ctx,next)=>{
        let roles = await userDao.getAllRoles();
        await ctx.render('addUser',{
            roles:roles,
            addinfo:ctx.session.addinfo
        })
    },
    saveUser:async(ctx,next)=>{
        let addResult = await indexService.saveUser(ctx.request.body);
        ctx.session.addinfo = addResult.info;
        ctx.response.redirect('/users/addUser');
    },
    defaultUserPass:async(ctx,next)=>{
        console.log(ctx.request.query);
        let salt = encryption.generateId();
        let encryPass = await encryption.getMd5Pass("123456",salt);
        let result = await userDao.updateUser(ctx.request.query.id,{
            password:encryPass,
            salt:salt
        })
        if(result){
            ctx.session.opUserInfo = "重置密码成功";
        }else{
            ctx.session.opUserInfo = "重置密码失败";
        }
        ctx.response.redirect('/users/userManage')
    },
    openUpdateUser:async(ctx,next)=>{
        let user = await userDao.findUserByPk(ctx.request.query.id);
        console.log("3333333")
        console.log(user.name)
        let roles = await userDao.getAllRoles();
        await ctx.render('updateUser',{
            roles:roles,
            updateuser:user,
            info:''
        })
    },
    updateUser:async(ctx,next)=>{
        let updateResult = await indexService.updateUser(ctx.request.body);
        let roles = await userDao.getAllRoles();
        updateResult.roles = roles;
        await ctx.render('updateUser',updateResult)
    },
    deleteUser:async(ctx,next)=>{
        let result = await userDao.deleteUser(ctx.request.query.id)
        if(result){
            ctx.session.opUserInfo = "删除用户成功";
        }else{
            ctx.session.opUserInfo = "删除用户失败";
        }
        ctx.response.redirect('/users/userManage')
    },
    loginGetToken:async(ctx,next)=>{
        const phone = ctx.request.body.phone;
        const password = ctx.request.body.password;
        if(phone && password){
            let user = await indexService.checkLogin(phone,password)
            if(user){
                let payload = {userid:user.id};
                let token = encryption.getUserToken(payload);
                if(token){
                    ctx.body = {success:true,
                        err:{code: 1,msg:'获取认证成功！'},
                        data:{
                            token:'Bearer '+ token
                        }
                    };
                }else{
                    ctx.body = {success:false,err:{ code: 0,msg:'获取认证失败!'}};
                }
            }else{
                ctx.body = {success:false,err:{ code: 0,msg:'用户不存在！'}};

                
            }
        }else{
            ctx.body = {success:false,err:{ code: 0,msg:'账户密码提交失败！'}};
    }
    
    }

}